package com.frogs.ucenter.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.PayCenterService;
import com.frogs.ucenter.util.Constants;
import com.frogs.ucenter.util.SignVerifyUtil;

@Service("payCenterService")
public class PayCenterServiceImpl extends AbsService implements PayCenterService {

	private static Logger log = LoggerFactory.getLogger(PayCenterServiceImpl.class);
	
	/**
	 * 获取支付渠道
	 */
	@Override
	public JSONArray getPayChannel() throws Exception {
		ApiUrl apiUrl = this.buildPayApiBaseUrl("PAY_PARTNER_INFO");
		Map<String, String> params = new HashMap<String, String>();
		params.put("uuid", payApiConfig.get("UUID"));
		params.put("token", payApiConfig.get("ACCESS_TOKEN"));
		String[] otherParams = {"sign", SignVerifyUtil.sign(params, Constants.PAY_SIGN_KEY).toLowerCase()};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONArray jsonArray = new JSONArray();
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getIntValue("ifSuc"))
				throw new IllegalStateException(result.getString(ResultParamEnum.tip.getParamName()));
			jsonArray = result.getJSONArray("data");
		} catch (IllegalStateException e) {
			log.error("func[addUserRechargeRecord] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取支付渠道接口请求失败！");
		}
		return jsonArray;
	}
}
